package org.lion.domain;

import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.lion.bean.LoginInfo;
import org.lion.proxy.input.student.HomeTaskInput;
import org.lion.proxy.input.student.LoginInput;
import org.lion.service.Client;
import org.lion.service.ClientConfig;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * Created by lion on 3/17/17.
 */
@Configuration
public class JavaConfig {

    @Bean
    public Client client(OkHttpClient okHttpClient) {
        return new Retrofit.Builder()
                .baseUrl(ClientConfig.BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .client(okHttpClient)
                .build()
                .create(Client.class);
    }

    @Bean
    public OkHttpClient okHttpClient() {
        OkHttpClient httpClient = new OkHttpClient().newBuilder()
                .connectTimeout(10000, TimeUnit.MILLISECONDS).writeTimeout(10000, TimeUnit.MILLISECONDS).readTimeout(10000, TimeUnit.MILLISECONDS)
                .addInterceptor(new Interceptor() {
                    @Override
                    public Response intercept(Chain chain) throws IOException {
                        String resolve_url = chain.request().url().toString();
                        String sessionId = userInfo().getSessionId();
                        String csrftoken = userInfo().getCsrftoken();
                        Request request = chain.request()
                                .newBuilder()
                                .addHeader("Cookie", "sessionid=" + sessionId)
                                .addHeader("Cookie", "csrftoken=" + csrftoken)
                                .url(chain.request().url().toString().replace("\\u003d", "%3d"))
                                .url(resolve_url.replace("\\u003d", "%3d"))
                                .build();
                        return chain.proceed(request);
                    }
                })
                .build();
        return httpClient;
    }

    @Bean
    public LoginInfo userInfo() {
        return new LoginInfo();
    }

    @Bean
    public LoginInput loginInput() {
        LoginInput input = new LoginInput();
        input.setOstype("0");
        input.setDevicetoken("a");
        input.setDescription("mi5");
        return input;
    }

    @Bean
    public HomeTaskInput homeTaskInput() {
        HomeTaskInput input = new HomeTaskInput();
        input.setAction("m_gettaskhomepagedata");
        input.setApi("2");
        return input;
    }
}
